package com.rbac.common.utils;

import com.rbac.domain.dto.response.MenuResponse;
import com.rbac.domain.entity.Menu;
import com.rbac.domain.entity.Permission;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TreeUtils {

    /**
     * 构建菜单树
     */
    public static List<MenuResponse> buildMenuTree(List<MenuResponse> menuList) {
        List<MenuResponse> result = new ArrayList<>();
        
        for (MenuResponse menu : menuList) {
            if (menu.getParentId() == null || menu.getParentId().equals(0L)) {
                menu.setChildren(getMenuChildren(menu, menuList));
                result.add(menu);
            }
        }
        
        return result;
    }
    
    private static List<MenuResponse> getMenuChildren(MenuResponse parent, List<MenuResponse> allMenus) {
        List<MenuResponse> children = new ArrayList<>();
        
        for (MenuResponse menu : allMenus) {
            if (parent.getId().equals(menu.getParentId())) {
                menu.setChildren(getMenuChildren(menu, allMenus));
                children.add(menu);
            }
        }
        
        return children.isEmpty() ? null : children;
    }

    /**
     * 构建菜单实体树
     */
    public static List<Menu> buildTree(List<Menu> menuList, Long parentId) {
        return menuList.stream()
                .filter(menu -> parentId.equals(menu.getParentId()))
                .peek(menu -> menu.setChildren(buildTree(menuList, menu.getId())))
                .collect(Collectors.toList());
    }

    /**
     * 构建权限树
     */
    public static List<Permission> buildPermissionTree(List<Permission> permissionList, Long parentId) {
        return permissionList.stream()
                .filter(permission -> parentId.equals(permission.getParentId()))
                .peek(permission -> permission.setChildren(buildPermissionTree(permissionList, permission.getId())))
                .collect(Collectors.toList());
    }
}